<style>
div.wrap * { font-size: 12px; font-family: Trebuchet MS; }
div.wrap { padding: 5px 15px 25px 15px; background: #fff; border: 1px solid #ddd; width: 96%; }
div.title { font-weight: bold; font-size: 16px; margin-bottom: 5px; font-family: Lucida Sans Unicode; }
.pure_form_extra label, .pure_form_extra input { font-size: 12px !important; font-family: Trebuchet MS; }
.pure_form_extra .mandatory { color: #ff0000; padding-left: 5px; }
.pure_form_extra { background: #fff; padding: 10px; border: 1px solid #aaa; border-radius: 8px; }
.pure_table_extra { width: 100%; }
.pure_table_list { width: 100%; border: 1px solid #aaa !important; }
.pure_table_list * { font-size: 12px !important; font-family: Trebuchet MS; }
div.title { font-weight: bold; font-size: 16px; margin-bottom: 5px; font-family: Lucida Sans Unicode; }
div.total { text-align: right; }
div.total div { border: 1px solid #ddd; background: #fff; padding: 5px 10px; width: 350px; margin: 5px 0 0 auto; font-size: 14px; font-weight: bold; }
div.total span.remind { display: block; color: #777; font-size: 12px; font-weight: normal; }
div.total span.remind a { color: #777; }
.pure_button_cart { margin-left: 5px; font-weight: bold; font-size: 14px !important; }
</style>

<?php
$user = null;
if (isset($_SESSION['user'])) {
  $user = json_decode($_SESSION['user']);
}

$currs = $orm->get('pb_ecom_currency', 't.title', 'ASC', NULL, NULL, NULL)->d;

$opts = new stdClass();
$opts->cd = 't.status = :v1';
$opts->cdv = array(':v1' => 1);
$couriers = $orm->get('pb_ecom_mthd_delivery', 't.title', 'ASC', NULL, NULL, $opts)->d;
$payments = $orm->get('pb_ecom_mthd_payment', 't.title', 'ASC', NULL, NULL, $opts)->d;

$cart = array();
if (isset($_SESSION['cart'])) {
	$cart = json_decode($_SESSION['cart']);
}
?>

<div class="wrap">
  <div class="title">最后完成订单...</div>
  <div class="pure-form pure-form-aligned pure_form_extra">
    <legend>货物清单</legend>
    
    <table class="pure-table pure_table_list" cellpadding=0 cellspacing=0>
      <thead>
        <tr>
          <th>商品</th>
          <th style="width: 60px;">单重(kg)</th>
          <th style="width: 80px;">数量</th>
          <th style="width: 60px;">单价</th>
          <th style="width: 90px;">总和</th>
        </tr>
      </thead>
      <tbody id="cart_body"></tbody>
    </table>
    <div class="total">
      <div>
        <span id="currs">
        <?php foreach ($currs as $itm) { ?>
          <input type="radio" id="curr_<?php echo $itm->title; ?>" onclick="update_curr(<?php echo $itm->id; ?>);" name="curr" /><label for="curr_<?php echo $itm->title; ?>"  style="margin-right: -5px !important;"><?php echo $itm->display_name; ?></label>
        <?php } ?>
        </span>
        总和: <span id="cart_total"></span>
        <?php if (!isset($_SESSION['user'])) { ?>
        <span class="remind">没有登录? 赶紧<a href="#" onclick="return Url.redirect(__redmd, __sys + '.php?i=' + __login_id + '&u=' + Utils.encodeURI(((parent != window) ? parent.document.URL : document.URL)));">登录</a> 或者 <a href="#" onclick="return Url.redirect(__redmd, __sys, __login_id, 'u=' + Utils.encodeURI(((parent != window) ? parent.document.URL : document.URL)));"">加入</a>我们，享受会员折扣</span>
        <?php } ?>
      </div>
    </div>
  </div>
  
  <div>&nbsp;</div>
  
  <div class="pure-form pure-form-aligned pure_form_extra">
    <legend>送货地址</legend>
    
    <table class="pure-table pure_table_list" cellpadding=0 cellspacing=0>
      <thead>
        <tr>
          <th style="width: 60px;">&nbsp;</th>
          <th style="width: 100px;">姓名</th>
          <th style="width: 100px;">城市</th>
          <th>地址</th>
          <th style="width: 100px;">电话</th>
          <th style="width: 100px;">邮箱</th>
          <th style="width: 60px;">&nbsp;</th>
        </tr>
      </thead>
      <tbody id="addr_body"></tbody>
      <tr>
        <td><input id="new_addr_btn" onclick="update_address(0);" type="radio" name="addr"' + ></input></th>
        <td colSpan=6>新地址</td>
      </tr>
      <tr id="new_addr"  style="display: none;">
        <td>&nbsp;</td>
        <td colSpan=6>
          <div>&nbsp;</div>
          <div class="pure-control-group">
            <label>姓名<span class="mandatory">*</span></label>
            <input id="addr_last" type="text" style="width: 200px;" placeholder="{family name}" />
            <input id="addr_first" type="text" style="width: 200px;" placeholder="{given name}" />
          </div>
          
          <div class="pure-control-group">
            <label>地址<span class="mandatory">*</span></label>
            <input id="addr_addr1" type="text" class="pure-input-1-2" placeholder="{Address}" />
          </div>
          
          <div class="pure-control-group">
            <label>地址2</label>
            <input id="addr_addr2" type="text" class="pure-input-1-2" placeholder="{Address2 (Optional)}" />
          </div>
          
          <div class="pure-control-group">
            <label>城市<span class="mandatory">*</span></label>
            <input id="addr_city" type="text" class="pure-input-1-2" placeholder="{City}" />
          </div>
          
          <div class="pure-control-group">
            <label>国家<span class="mandatory">*</span></label>
            <input id="addr_country" type="text" class="pure-input-1-2" placeholder="{Country}" />
          </div>
          
          <div class="pure-control-group">
            <label>邮编<span class="mandatory">*</span></label>
            <input id="addr_zip" type="text" class="pure-input-1-2" placeholder="{Post Code}" />
          </div>
          
          <div class="pure-control-group">
            <label>电话<span class="mandatory">*</span></label>
            <input id="addr_phone" type="text" class="pure-input-1-2" placeholder="{Phone}" />
          </div>
          
          <div class="pure-control-group">
            <label>邮箱<span class="mandatory">*</span></label>
            <input id="addr_email" type="text" class="pure-input-1-2" placeholder="{Email}" />
          </div>
        </td>
      </tr>
    </table>
  </div>
    
  
  <div>&nbsp;</div>
  
  <div class="pure-form pure-form-aligned pure_form_extra">
    <legend>送货方式</legend>
    
    <table class="pure-table pure_table_extra" cellPadding="0" cellSpacing="0">
      <thead>
        <tr>
          <th style="width: 60px;">&nbsp;</th>
          <th style="width: 150px;">快递公司</th>
          <th>备注</th>
          <th style="width: 150px;">价格</th>
        </tr>
      </thead>
      <tbody id="couriers_body"></tbody>
    </table>
  </div>
    
  <div>&nbsp;</div>
  
  <div class="pure-form pure-form-aligned pure_form_extra">
    <legend>支付方式</legend>
    
    <table class="pure-table pure_table_extra" cellPadding="0" cellSpacing="0">
      <thead>
        <tr>
          <th style="width: 60px;">&nbsp;</th>
          <th>支付</th>
        </tr>
      </thead>
      <tbody id="payments_body"></tbody>
    </table>
  </div>
  
  <div>&nbsp;</div>
  
  <div class="pure-form pure-form-aligned pure_form_extra">
    <legend>留言（请留下寄件人的联系方式 比如：手机，邮箱）</legend>
    
    <textarea id="comment" style="width: 100%; resize: none; height: 150px;"></textarea>
  </div>
  
  <div>&nbsp;</div>
  
  <button onclick="Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=index_cart');" class="pure-button pure-button-active pure_button_cart"><i class="fa fa-shopping-cart fa-lg"></i>&nbsp;返回购物车</button>
  <button style="float: right;" onclick="create_order(event);" class="pure-button pure-button-active pure_button_cart"><i class="fa fa-check fa-lg"></i>&nbsp;生成订单</button>
  
</div>

<div>&nbsp;</div>

<div id="dialog_addr" class="pure-form pure-form-aligned pure_form_extra" style="display: none;" title="更新地址">
  <div class="pure-control-group">
    <label>姓名<span class="mandatory">*</span></label>
    <input id="addr_last_chg" type="text" style="width: 100px;" placeholder="{family name}" />
    <input id="addr_first_chg" type="text" style="width: 100px;" placeholder="{given name}" />
  </div>
  
  <div class="pure-control-group">
    <label>地址<span class="mandatory">*</span></label>
    <input id="addr_addr1_chg" type="text" class="pure-input-1-2" placeholder="{Address}" />
  </div>
  
  <div class="pure-control-group">
    <label>地址2</label>
    <input id="addr_addr2_chg" type="text" class="pure-input-1-2" placeholder="{Address2 (Optional)}" />
  </div>
  
  <div class="pure-control-group">
    <label>城市<span class="mandatory">*</span></label>
    <input id="addr_city_chg" type="text" class="pure-input-1-2" placeholder="{City}" />
  </div>
  
  <div class="pure-control-group">
    <label>国家<span class="mandatory">*</span></label>
    <input id="addr_country_chg" type="text" class="pure-input-1-2" placeholder="{Country}" />
  </div>
  
  <div class="pure-control-group">
    <label>邮编<span class="mandatory">*</span></label>
    <input id="addr_zip_chg" type="text" class="pure-input-1-2" placeholder="{Post Code}" />
  </div>
  
  <div class="pure-control-group">
    <label>电话<span class="mandatory">*</span></label>
    <input id="addr_phone_chg" type="text" class="pure-input-1-2" placeholder="{Phone}" />
  </div>
  
  <div class="pure-control-group">
    <label>邮箱<span class="mandatory">*</span></label>
    <input id="addr_email_chg" type="text" class="pure-input-1-2" placeholder="{Email}" />
  </div>
</div>

<script type="text/javascript">
  var __user = JSON.parse('<?php echo addslashes(json_encode($user)); ?>');
  var __cart = JSON.parse('<?php echo addslashes(json_encode($cart)); ?>');
  var __currs = JSON.parse('<?php echo addslashes(json_encode($currs)); ?>');
  var __couriers = JSON.parse('<?php echo addslashes(json_encode($couriers)); ?>');
  var __payments = JSON.parse('<?php echo addslashes(json_encode($payments)); ?>');
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __login_id = '<?php echo $app_data->__login_id; ?>';
  var __curr, __address, __courier, __payment, __total;
  
  $(function(){
    Utils.init_ecomm();

    if (__user && __user.__addrs && __user.__addrs.length > 0) {
      __address = __user.__addrs[0];
    }
    
    if (__couriers.length > 0) {
      __courier = __couriers[0];
    }
    
    reset();
    render();
  });

  function reset() {
    for (var idx in __payments) {
      var itm = __payments[idx];
      if (itm.curr_id.indexOf(__curr.title) == -1) {
        continue;
      }
      __payment = itm;
      return;
    }
  };

  function render() {
    render_cart();
    render_addrs();
    render_couriers();
    render_payments();
  };

  function render_addrs() {
    $('#addr_body').empty();
    var ex = 0;
    if (__user) {
      for (var idx in __user.__addrs) {
        var itm = __user.__addrs[idx];
        $('#addr_body').append(
          '<tr class="' + ((idx % 2 ==0) ? 'pure-table-even' : 'pure-table-odd') + '">' +
            '<td><input onclick="update_address(' + itm.id + ');" type="radio" name="addr"' + (((!__address && itm.is_default == 1) || (__address && __address.id == itm.id)) ? ' checked="checked"' : '') + '></input></td>' +
            '<td>' + itm.last_name + ' ' + itm.first_name + '</td>' +
            '<td>' + itm.city + '</td>' +
            '<td>' + itm.address1 + '</td>' +
            '<td>' + itm.phone + '</td>' +
            '<td>' + itm.email + '</td>' +
            '<td><i style="cursor: pointer; margin-right: 5px;" class=" fa fa-pencil" onclick="update_addr(' + itm.id + ', event)"></i><i style="cursor: pointer;" class="icon-remove-sign icon-large" onclick="delete_addr(' + itm.id + ')"></i></td>' +
          '</tr>'
        );
        ex = 1;
      }
    }
    if (!__address) {
      $('#new_addr_btn').prop('checked', true);
      $('#new_addr').show();
    } else {
      $('#new_addr').hide();
    }
  };

  function render_cart() {
    $('#cart_body').empty();
    var total = 0;
    var weight = 0;
    for (var idx in __cart) {
      var itm = __cart[idx];
      itm.__fp = Utils.get_price(__currs, itm.curr, __curr.title, itm.price, itm.__enabled_member == 1 ? (__user ? __user.__discount : null) : null);
      itm.total = itm.__fp * itm.quantity;
      total += itm.total;
      weight += parseFloat(itm.weight, 10);
      $('#cart_body').append(
        '<tr class="' + ((idx % 2 ==0) ? 'pure-table-even' : 'pure-table-odd') + '">' +
          '<td>' + itm.name + ((itm.attr_opt_code != '') ? ' (' + itm.attr_opt_code + ')' : '') + '</td>' +
          '<td>' + accounting.formatNumber(itm.weight) + '</td>' +
          '<td>' + accounting.formatNumber(itm.quantity) + '</td>' +
          '<td>' + accounting.formatMoney(itm.__fp, __curr.dollar_symbol) + '</td>' +
          '<td>' + accounting.formatMoney(itm.total, __curr.dollar_symbol) + '</td>' +
        '</tr>'
      );
    }
    
    __total = total;
    
    $('#cart_total').html(accounting.formatMoney(total, __curr.dollar_symbol) + ' (' + weight + 'kg)');
    
    if (__cart.length == 0) {
      $('#cart_body').append('<tr class="roweven"><td colSpan="5">您的购物车为空</td></tr>')
    }
  };

  function render_couriers() {
    $('#couriers_body').empty();
    for (var idx in __couriers) {
      var itm = __couriers[idx];
      $('#couriers_body').append(
        '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' +
          '<td><input onclick="update_courier(' + itm.id + ');" type="radio" name="courier"' + ((__courier.id == itm.id) ? ' checked="checked"' : '') + '></input></td>' +
          '<td>' + itm.title + '</td>' +
          '<td>' + itm.description + '</td>' +
          '<td>' + accounting.formatMoney(__delivery_cost(itm), __curr.dollar_symbol) + '</td>' +
        '</tr>'
      );
    }
  };

  function render_payments() {
    $('#payments_body').empty();
    var count = 0;
    for (var idx in __payments) {
      var itm = __payments[idx];
      if (itm.curr_id.indexOf(__curr.title) == -1) {
        continue;
      }
      $('#payments_body').append(
        '<tr class="' + ((count % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' +
          '<td><input onclick="update_payment(' + itm.id + ');" type="radio" name="payment"' + ((__payment.id == itm.id) ? ' checked="checked"' : '') + '></input></td>' +
          '<td>' + itm.title + '</td>' +
        '</tr>'
      );
      count++;
    }
  };

  function update_address(id) {
    if (__user) {
      __address = Utils.get_by_id(id, __user.__addrs);
    } else {
      __address = null;
    }
    render_addrs();
  };
  
  function update_courier(id) {
    __courier = Utils.get_by_id(id, __couriers);
  };

  function update_payment(id) {
    __payment = Utils.get_by_id(id, __payments);
  };
  

  function __delivery_cost(courier) {
    var weight = 0;
    for (var idx in __cart) {
      var itm = __cart[idx];
      weight += parseFloat(itm.weight, 10);
    }
    if (weight <= courier.min_weight) {
      return Utils.get_price(__currs, courier.curr, __curr.title, courier.min_price, null);
    }
    return Utils.get_price(__currs, courier.curr, __curr.title, parseFloat(courier.min_price, 10) + ((weight - courier.min_weight) * courier.price), null);
  };

  function update_curr(id) {
    __curr = Utils.get_by_id(id, __currs);
    Cookie.set_cookie('curr', JSON.stringify(__curr), 1);

    if (__payment.curr_id.indexOf(__curr.title) == -1) {
      reset();
    }
    render();
  };

  function create_order(ev) {
    var req = {
      ship_date: '0000-00-00',
      ship_track: '',
      customer_id: __user ? __user.id : 0,
      order_number: '',
      is_paid: 0,
      is_cancel: 0,
      curr: __curr.title,
      total: __total,
      comment: $('#comment').val(),
      payment_id: __payment.id,
      payment_name: __payment.title,
      payment_code: __payment.code,
      delivery_id: __courier.id,
      delivery_name: __courier.title,
      delivery_subtotal: __delivery_cost(__courier)
    };
    if (__address) {
      req = __merge(__address, req);
      delete req.is_default;
      delete req.id;
    } else {
      var address = {
        first_name: $('#addr_first').val(),
        last_name: $('#addr_last').val(),
        address1: $('#addr_addr1').val(),
        address2: $('#addr_addr2').val(),
        city: $('#addr_city').val(),
        country: $('#addr_country').val(),
        zip: $('#addr_zip').val(),
        phone: $('#addr_phone').val(),
        email: $('#addr_email').val()
      };
      req =  __merge(address, req);
      if (__user) {
        req.__newaddr = Utils.clone(address);
        req.__newaddr.is_default = (__user.__addrs.length > 0) ? 0 : 1;
        req.__newaddr.customer_id = __user.id;
      }
    }
    req.__purchases = __cart;
    
    Ajax.request(
      __requrl + 'create_order',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __cart = [];
        Utils.set_cartnum(__cart);
        Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=index_paynow&od=' + rslt.order_number);
      },
      { confirm: 1, txt: '确定生成新订单么?', tt: '请确认', ld: '生成订单中...' }
    );
  };

  function delete_addr(id) {
    if (__address && id == __address.id) {
      __address = null;
    }
    req = Utils.get_by_id(id, __user.__addrs);
    Ajax.request(
      __requrl + 'delete_addr',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        reset();
        render_addrs();
      },
      { confirm: 1, txt: '确定删除改地址么?', tt: '请确认'}
    );
  };

  function update_addr(id, ev) {
    var func = function() {
      var req = Utils.get_by_id(id, __user.__addrs);
      req.first_name = $('#addr_first_chg').val();
      req.last_name = $('#addr_last_chg').val();
      req.address1 = $('#addr_addr1_chg').val();
      req.address2 = $('#addr_addr2_chg').val();
      req.city = $('#addr_city_chg').val();
      req.country = $('#addr_country_chg').val();
      req.zip = $('#addr_zip_chg').val();
      req.phone = $('#addr_phone_chg').val();
      req.email = $('#addr_email_chg').val();

      Ajax.request(
        __requrl + 'update_addr',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          reset();
          render_addrs();
          $('#dialog_addr').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_addr').dialog({
      width: 500,
      position: {
        my: 'left-300 bottom+0',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });

    var obj = Utils.get_by_id(id, __user.__addrs);

    $('#dialog_addr input')[0].onkeypress = function(ev) { if(ev.which == 13) { func(); } };

    $('#addr_first_chg').val(obj.first_name);
    $('#addr_last_chg').val(obj.last_name);
    $('#addr_addr1_chg').val(obj.address1);
    $('#addr_addr2_chg').val(obj.address2);
    $('#addr_city_chg').val(obj.city);
    $('#addr_country_chg').val(obj.country);
    $('#addr_zip_chg').val(obj.zip);
    $('#addr_phone_chg').val(obj.phone);
    $('#addr_email_chg').val(obj.email);
  };

  function __merge(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
  };
  
</script>